package com.gome.cloud.service;

import com.gome.cloud.entity.User;
import com.google.gson.Gson;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author supan
 * @Date 2017/6/9 17:45
 * @Copyright(c) gome inc Gome Co.,LTD
 */
@Service
public class RibbonService {

    private static Gson gson = new Gson();
    private static final Logger LOGGER = LoggerFactory.getLogger(RibbonService.class);
    @Autowired
    public RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;

    //@HystrixCommand注解来指定回调方法
    @HystrixCommand(fallbackMethod = "addServiceFallback")
    public String add(){
        LOGGER.info("Ribbon消费方法: method add()");
        String requestURL = "http://service-provider/add?a=10&b=12";
        return restTemplate.getForEntity(requestURL,String.class).getBody();
    }
    public String addServiceFallback() {
        LOGGER.info("异常发生，进入addServiceFallback方法,返回自定义的响应结果");
        return "error";
    }
    @HystrixCommand(fallbackMethod = "findUserByIdFallback")
    public User findUserById(Long id){
        long start = System.currentTimeMillis();
        String requestURL = "http://service-provider/user/"+ id;
        String url = loadBalancerClient.choose("service-provider").getUri().toString() + "/user/" + id;
        LOGGER.info("Ribbon消费方法: method findUserById() args:id = {} url={}",id,url);
        User user =  this.restTemplate.getForObject(requestURL,User.class);
        long end = System.currentTimeMillis();
        LOGGER.info("Spent time：" + (end-start));
        return user;
    }
    public User findUserByIdFallback(Long id) {
        RibbonService.LOGGER.info("异常发生，进入fallback方法，接收的参数：id = {},返回自定义的响应用户信息",id);
        User user = new User();
        user.setId(-1L);
        user.setUsername("default username");
        user.setAge(0);
        return user;
    }
    public List<User> findAll() {
           LOGGER.info("Ribbon消费方法: method findAll()");
           return this.restTemplate.getForObject("http://service-provider/users",List.class);
    }


}
